// scanPlugin.ts
import {Plugin} from "esbuild";
import {BARE_IMPORT_RE,EXTERNAL_TYPES} from "../constants";

export function scanPlugin(deps:Set<string>):Plugin {
    return {
        name:"scan-deps",
        setup(build){

            //过滤掉了无关的资源，他是将 EXTERNAL_TYPES 数组中所有相关的后缀名全部过滤掉
            build.onResolve({filter:new RegExp(`\\.(${EXTERNAL_TYPES.join("|")})$`)},resolveInfo=>{
                // console.log("resolveInfo external part 1",resolveInfo);
                return{
                    path:resolveInfo.path,
                    external:true
                }
            });

            //第一个字符必须是字母、数字、下划线 (_) 或者 @。这由 [\\w@] 部分表示
            // ,第二个字符不能是冒号 (:)。这由 [^:] 部分表示
            build.onResolve({filter:BARE_IMPORT_RE},resolveInfo=>{
                // console.log("resolveInfo external part 2",resolveInfo);
                const { path: id } = resolveInfo;
                // console.log("resolveInfo part 2 id",id);
                deps.add(id);
                return{
                    path:id,
                    external:true
                }
            })
        }
    }
}
